<template>
	<view>
		<view style="width: 100%;padding-bottom: 140rpx;">
			<!-- 遍历消息记录 -->
			<view style="display: flex;flex-direction: column;" v-for="(chat,index) in chatRecord.data">
				<view v-if="index%5==0"
					style="margin-top: 15rpx;width: 100%;text-align: center;font-size: 26rpx;color: #999999;">
					{{chat.time}}
				</view>

				<!-- 我的消息 -->
				<view v-if="chat.sendId==user.id" style="width: 83%;margin-left: 15%;">
					<view class="chat-listitem" style="float: right;">
						<!-- 文字信息 -->
						<view v-if="chat.msg" @longpress="copy(chat.msg)" class="chat-listitem-text"
							style="margin-right: 20rpx;">{{chat.msg}}
						</view>

						<!-- 图片信息 -->
						<!-- <image @tap="viewImg(item.content)" v-if="item.content && item.type === 2"
								:src="item.content" style="height: 200rpx;width: 200rpx;margin-right: 20rpx;">
							</image> -->

						<!-- 头像 -->
						<view>
							<image v-if="user.avr" :src="user.avr" class="chat-listitem-image"></image>
							<image v-else src="../../static/logo.png" class="chat-listitem-image"></image>
						</view>
					</view>
				</view>

				<!-- 对方的消息 -->
				<view v-if="chat.sendId == aceeptUser.id" style="width: 83%;margin-right: 15%;">
					<view class="chat-listitem" style="float: left;margin-left: 10rpx;">
						<!-- 头像 -->
						<view>
							<image v-if="aceeptUser.avr" :src="aceeptUser.avr" class="chat-listitem-image"
								style="margin-left: 20rpx;"></image>
							<image v-else src="../../static/logo.png" class="chat-listitem-image"
								style="margin-left: 20rpx;"></image>
						</view>
						<!-- 文字信息 -->
						<view v-if="chat.msg" @longpress="copy(chat.msg)" class="chat-listitem-text"
							style="margin-left: 20rpx;">{{chat.msg}}
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部聊天输入框 -->
		<view class="input-box padding-tb">
			<view class="justify-between padding-lr"
				style="display: flex;margin-top: 15rpx;width: 100%;background-color: #1c1b20;padding-top: 14upx;">
				<!-- 	<image src="../../static/add.png" @click="chooseImage(['album'])"
					style="width: 60rpx;height: 60rpx;margin-top: 8rpx;"></image> -->
				<input confirm-type="send" @confirm='setChatSave(1)' type="text" v-model="content"
					style="width: 72%;height: 70rpx;background: #3B3D55;margin: 4rpx 10rpx 0;border-radius: 70rpx;padding-left: 10rpx;color: #FFF;" />
				<view class="save" @tap='setChatSave(1)'>发送</view>
			</view>
		</view>
	</view>
</template>

<script>
	// import configdata from '../../common/config.js';
	export default {
		data() {
			return {
				//用户自己
				user: {
					"id": "",
					"account": ""
				},
				//接受消息的用户
				aceeptUser: {
					"id": "",
					"account": "",
					"nick": "未连接"
				},
				chatRecord: null,
				//我发送的消息内容
				content: '',



				//原始数据
				connected: false,
				connecting: false,
				msg: false,
				type4: [],
				listRight: {
					chat: {
						userHead: ""
					},
					content: "",
					sendType: 1,
					type: 1
				},
				// content: '',
				chatId: '',
				type: 1,
				ListItem: [],
				ShopState: false,
				ShopordersId: '',
				Shopimage: '',
				Shopmoney: '',
				ShopTitle: '',
				orderState: false,
				ordersId: '',
				userId: '',
				orderimage: '',
				orderNum: '',
				teamId: '',
				hand: 1,
				index: 0,
				page: 1,
				size: 1000,
				countDown: ''
			};
		},

		computed: {
			showMsg() {
				if (this.connected) {
					if (this.msg) {
						return '收到消息：' + this.msg
					} else {
						return '等待接收消息'
					}
				} else {
					return '尚未连接'
				}
			}
		},
		onUnload() {
			// 关闭 WebSocket 连接
			uni.closeSocket()
			uni.hideLoading()
		},
		onLoad(option) {
			this.user.id = uni.getStorageSync("userId");
			//TODO 
			// this.user.id = 1;
			this.aceeptUser.id = option.id;
			console.log(option.id);
			//TODO根据这两个id，来查询跟此对方用户的昵称、最近的10条聊天记录（按照一行一行来算）
			//(1) 查询自己的用户信息
			this.$myRequest({
				url: "/user/byId",
				method: "get",
				data: {
					"id": this.user.id
				}
			}).then(r => {
				if (r.data.code == "200") {
					this.user = r.data.data;
				} else {
					uni.showToast({
						title: "系统繁忙",
						//将值设置为 success 或者直接不用写icon这个参数
						icon: 'fail',
						//显示持续时间为 2秒
						duration: 2000
					})
				}
				console.log("user");
				console.log(this.user);
			})

			//(2)查询对方的用户信息
			this.$myRequest({
				url: "/user/byId",
				method: "get",
				data: {
					"id": this.aceeptUser.id
				}
			}).then(r => {
				if (r.data.code == "200") {
					this.aceeptUser = r.data.data;

					//设置导航栏名称，设置聊天人的昵称
					uni.setNavigationBarTitle({
						title: this.aceeptUser.nick
					});

				} else {
					uni.showToast({
						title: "系统繁忙",
						//将值设置为 success 或者直接不用写icon这个参数
						icon: 'fail',
						//显示持续时间为 2秒
						duration: 2000
					})
				}
				console.log("aceeptUser");
				console.log(this.aceeptUser);
			})

			//连接后台websocket
			this.connect();
		},
		onShow() {
			if (this.connected || this.connecting) {

			} else {
				this.connect();
			}
		},
		onHide() {
			// 关闭 WebSocket 连接
			uni.closeSocket()
		},
		onPullDownRefresh() {
			console.log("上一页")
			this.page++;
			this.$myRequest({
				url: "/chat/getChatRecord",
				method: "post",
				data: {
					"sendUser": {
						"id": this.user.id
					},
					"acceptUser": {
						"id": this.aceeptUser.id
					},
					"pageNum": this.page
				}
			}).then(r => {
				if (r.data.code == "200") {
					// this.chatRecord.unshift(r.data.data);
					console.log(this.chatRecord.data)
					r.data.data.data.forEach(c => {
						c.time = this.getDateDiff(c.time)
					})
					this.chatRecord.data = r.data.data.data.concat(this.chatRecord.data);
					console.log(this.chatRecord.data)
					//把最近的聊天记录获取到，然后把他们的时间进行转换

				} else {
					uni.showToast({
						title: "系统繁忙",
						//将值设置为 success 或者直接不用写icon这个参数
						icon: 'fail',
						//显示持续时间为 2秒
						duration: 2000
					})
				}
			})
			uni.stopPullDownRefresh();
		},
		methods: {

			copy(content) {
				uni.showModal({
					title: '温馨提示',
					content: '确认要复制此文字吗？',
					showCancel: true,
					cancelText: '取消',
					confirmText: '确认',
					success: res => {
						if (res.confirm) {
							uni.setClipboardData({
								data: content,
								success: r => {
									this.$queue.showToast('复制成功');
								}
							});
						}
					}
				});
			},


			//连接webSocket
			connect() {
				console.log("执行connect()方法")

				let userId = this.user.id;
				let that = this;

				if (this.connected || this.connecting) {
					uni.showModal({
						content: '正在连接或者已经连接，请勿重复连接',
						showCancel: false
					})
					return false
				}

				this.connecting = true

				uni.showLoading({
					title: '连接中...'
				})


				//连接websocket,开启一个websocket服务
				uni.connectSocket({
					// url: 'ws://localhost:9090/gameTeamChat/' + userId + '_' + this.teamId,
					// url: 'wss://game.shengqianxiong.com.cn/wss/gameTeamChat/' + userId + '_' + this.teamId,
					url: 'ws://localhost:8080/imserver/' + this.user.id,
					data() {
						return {
							msg: 'Hello'
						}
					},
					header: {
						'content-type': 'application/json'
					},
					method: 'GET',
					success(res) {
						console.log('connectSocket：执行成功')
						that.getNewestChatRecord();
						// 这里是接口调用成功的回调，不是连接成功的回调，请注意
					},
					fail(err) {
						console.log('connectSocket：执行失败')
						// 这里是接口调用失败的回调，不是连接失败的回调，请注意
					}
				})

				//监听WebSocket连接打开事件。
				uni.onSocketOpen((res) => {
					console.log('onSocketOpen：监听WebSocket连接打开事件');
					console.log("onSocketOpen：连接websocket服务器成功")
					this.connecting = false
					this.connected = true
					uni.hideLoading()
					uni.showToast({
						icon: 'none',
						title: '连接成功'
					})
					console.log('onOpen', res);
				})

				//监听WebSocket接受到服务器的消息事件。
				uni.onSocketMessage(function(r) {
					console.log('onSocketMessage：监听WebSocket接受到服务器的消息事件');

					console.log('收到服务器内容：');
					console.log(r.data);

					let data = JSON.parse(r.data);
					console.log(data);

					//将发送的消息加入到最近的消息列表中,消息列表只保存显示10条，所以把第一条删除，然后加入最新的一条
					//删除第一条消息记录
					that.chatRecord.data.shift()
					let chat = {
						sendId: data.sendId,
						acceptId: that.user.id,
						msg: data.content,
						time: that.getDateDiff(new Date())
					}
					//将消息新增
					that.chatRecord.data.push(chat);

					console.log("chatRecord")
					console.log(that.chatRecord.data)

				});

				//监听WebSocket错误
				uni.onSocketError((err) => {
					console.log('onSocketError：监听WebSocket错误');
					this.connecting = false
					this.connected = false
					uni.hideLoading()
					uni.showModal({
						content: '网络较差，请稍后再试',
						showCancel: false
					})
					console.log('onError', err);
				})

				//监听WebSocket关闭
				uni.onSocketClose((res) => {
					console.log('onSocketClose：监听WebSocket关闭');
					this.connected = false
					this.startRecive = false
					this.msg = false
					console.log('onClose', res)
				})
			},

			//关闭聊天的webSocket
			close() {
				console.log('closeSocket：关闭聊天的webSocket');
				// 关闭 WebSocket 连接
				uni.closeSocket()
			},



			//发送聊天消息
			setChatSave(type) {
				console.log('执行setChatSave：发送聊天消息');

				//判断发送消息方的内容是否为空，是否有效
				if (this.content == undefined || this.content == null || this.content.trim() == '') {
					console.log('执行setChatSave：无效内容');
					return;
				}

				let that = this;


				// //type:1文字 2图片
				// if (type === 1 && this.content == '') {
				// 	this.$queue.showToast('请输入聊天内容');
				// 	return;
				// }

				//判断发送消息方的id和接受消息放的id，是否有效
				if (this.user.id == undefined || this.user.id == null || this.user.id == '' ||
					this.aceeptUser.id == undefined || this.aceeptUser.id == null || this.aceeptUser.id == ''
				) {
					uni.showLoading({
						title: '网络较差，请稍后再试'
					});
					return;
				}


				let data = {
					acceptId: this.aceeptUser.id,
					content: this.content
				}

				let msg = this.content;

				//转成json格式的字符串（因为后台只接受字符串）
				data = JSON.stringify(data);
				console.log(data);
				// 通过 WebSocket 连接发送数据，需要先启动uni.connectSocket，并在uni.onSocketOpen回调之后才能发送。
				// 浏览器端收消息，获得从服务端发送过来的文本消息
				uni.sendSocketMessage({
					data: data,
					success(res) {
						console.log(res);
						//清除下输入框的内容
						that.content = '';


						//将发送的消息加入到最近的消息列表中,消息列表只保存显示10条，所以把第一条删除，然后加入最新的一条
						//删除第一条消息记录
						that.chatRecord.data.shift()
						let chat = {
							sendId: that.user.id,
							acceptId: that.aceeptUser.id,
							msg: msg,
							time: that.getDateDiff(new Date())
						}
						//将消息新增
						that.chatRecord.data.push(chat);



						console.log("chatRecord")
						console.log(that.chatRecord.data)
					},
					fail(err) {
						console.log(err);
					}
				})
			},

			//获取最新的聊天记录
			getNewestChatRecord(pageNum) {
				console.log('执行getNewestChatRecord');

				//(3)查询双方的聊天记录
				this.$myRequest({
					url: "/chat/getChatRecord",
					method: "post",
					data: {
						"sendUser": {
							"id": this.user.id
						},
						"acceptUser": {
							"id": this.aceeptUser.id
						},
						"pageNum": pageNum
					}
				}).then(r => {
					if (r.data.code == "200") {
						this.chatRecord = r.data.data;
						//把最近的聊天记录获取到，然后把他们的时间进行转换
						this.chatRecord.data.forEach(c => {
							c.time = this.getDateDiff(c.time)
						})

					} else {
						uni.showToast({
							title: "系统繁忙",
							//将值设置为 success 或者直接不用写icon这个参数
							icon: 'fail',
							//显示持续时间为 2秒
							duration: 2000
						})
					}
					console.log("chatRecord")
					console.log(this.chatRecord);
				})


			},

			//通过时间来转换成，最后的聊天记录距现在的时间差
			getDateDiff(data) {
				// 传进来的data必须是日期格式，不能是时间戳
				//var str = data;
				//将字符串转换成时间格式
				var timePublish = new Date(data);
				var timeNow = new Date();
				var minute = 1000 * 60;
				var hour = minute * 60;
				var day = hour * 24;
				var month = day * 30;
				var result = "2";

				var diffValue = timeNow - timePublish;
				var diffMonth = diffValue / month;
				var diffWeek = diffValue / (7 * day);
				var diffDay = diffValue / day;
				var diffHour = diffValue / hour;
				var diffMinute = diffValue / minute;


				if (diffMonth > 3) {
					result = timePublish.getFullYear() + "-";
					result += timePublish.getMonth() + "-";
					result += timePublish.getDate();
				} else if (diffMonth > 1) { //月
					result = data.substring(0, 10);
				} else if (diffWeek > 1) { //周
					result = data.substring(0, 10);
				} else if (diffDay > 1) { //天
					result = data.substring(0, 10);
				} else if (diffHour > 1) { //小时
					result = parseInt(diffHour) + "小时前";
				} else if (diffMinute > 1) { //分钟
					result = parseInt(diffMinute) + "分钟前";
				} else {
					result = "刚刚";
				}
				return result;
			},


			//发送图片
			chooseImage(sourceType) {
				console.log('执行chooseImage：发送图片');
				uni.chooseImage({
					count: 1,
					sourceType: ['album', 'camera'],
					success: res => {
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							uni.showLoading({
								title: '上传中...'
							})
							uni.uploadFile({ // 上传接口
								url: this.config("APIHOST1") + '/alioss/upload', //真实的接口地址
								filePath: res.tempFilePaths[i],
								name: 'file',
								success: (uploadFileRes) => {
									this.content = JSON.parse(uploadFileRes.data).data;
									this.setChatSave(2);
									uni.hideLoading();
								}
							});
						}
					}
				})
			},
			config: function(name) {
				var info = null;
				if (name) {
					var name2 = name.split("."); //字符分割
					if (name2.length > 1) {
						info = configdata[name2[0]][name2[1]] || null;
					} else {
						info = configdata[name] || null;
					}
					if (info == null) {
						let web_config = cache.get("web_config");
						if (web_config) {
							if (name2.length > 1) {
								info = web_config[name2[0]][name2[1]] || null;
							} else {
								info = web_config[name] || null;
							}
						}
					}
				}
				return info;
			},
			//查看大图
			viewImg(item) {
				let imgsArray = [];
				imgsArray[0] = item;
				uni.previewImage({
					current: 0,
					urls: imgsArray
				});
			},
		},
	};
</script>

<style>
	.input-box {
		position: fixed;
		bottom: 0;
		left: 0;
		height: 120rpx;
		width: 100%;
		display: flex;
		box-sizing: content-box;
		z-index: 999;
		/* background-color: #ececec; */
		padding: 0 5rpx;
	}

	.chat-listitem {
		display: flex;
		margin-top: 20rpx;
		padding: 10rpx;
	}

	.chat-listitem-text {
		color: #ececec;
		background: #1E1F31;
		margin-top: 10rpx;
		width: fit-content;
		padding: 15rpx;
		font-size: 30rpx;
		height: max-content;
		word-wrap: break-word;
		word-break: break-all;
		border-radius: 10rpx;
	}

	.chat-listitem-image {
		margin-top: 5rpx;
		width: 75rpx;
		height: 75rpx;
		border-radius: 5rpx;
	}

	.save {
		width: 130rpx;
		text-align: center;
		border-radius: 70rpx;
		height: 70rpx;
		color: #FFF;
		background: #1789FD;
		margin: 5rpx 10rpx 0;
		line-height: 70rpx;
	}
</style>
